'use strict'

const {isFunction} = require('is-type-of')
const {appService} = require('../app')
const {BrowserWindow, dialog, shell} = require('electron')
const {merge} = require('lodash')
const {logger} = require('ee-core/log')
const {getConfig} = require('ee-core/config')

//阻止窗口标题栏右键默认上下文菜单
const preventTitleBarContextMenuFunc = (browserWin, callback = null) => {
    browserWin.on('system-context-menu', (event, point) => {
        event.preventDefault()
        if (isFunction(callback)) {
            callback.call()
        }
    })
}

//注册网页<a target="_blank">标签和window.open拦截处理器
const registerWindowOpenHandler = (browserWin) => {
    const maxOpenCount = 10
    const denyRet = {action: 'deny'}
    browserWin.webContents.setWindowOpenHandler(({url}) => {
        if (url === 'about:blank') {
            if (BrowserWindow.getAllWindows().length > maxOpenCount) {
                dialog.showMessageBox(browserWin, {
                    title: '提示',
                    detail: '窗口最多可同时开启' + maxOpenCount + '个! ^_^'
                })
                return denyRet
            }

            //默认 overrideBrowserWindowOptions
            const OPTIONS = {}
            merge(OPTIONS, getConfig().windowsOption)
            OPTIONS.show = true
            // todo: 这个配置好像被electron后期更新删除掉了？？？
            OPTIONS.zoomFactor = appService.appZoomFactor
            OPTIONS.backgroundColor = appService.appBackgroundColor

            const windowRectangle = browserWin.getNormalBounds()
            OPTIONS.x = windowRectangle.x < 150 ? (windowRectangle.x + 50) : (windowRectangle.x - 50)
            OPTIONS.y = windowRectangle.y < 150 ? (windowRectangle.y + 50) : (windowRectangle.y - 50)

            return {
                action: 'allow',
                overrideBrowserWindowOptions: OPTIONS
            }
        } else {
            shell.openPath(url).then(error => {
                if (error !== '') {
                    logger.error('[browser:registerWindowOpenHandler]', error)
                }
            })
        }

        return denyRet
    })
}


module.exports = {
    preventTitleBarContextMenuFunc,
    registerWindowOpenHandler
}